package org.sam.swing.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 文件操作工具助手工具类
 * 
 * @author sam
 *
 */
public class FileUtils {

	/**
	 * 复制资源文件并且写入到临时文件里
	 * 
	 * @param is
	 *            输入资源文件流
	 * @return
	 * @throws Exception
	 */
	public static File copyResourceToTempFile(String name, String suffix, InputStream is) throws Exception {
		if (is == null)
			throw new RuntimeException("传入资源文件有误");

		File temp = File.createTempFile(name, suffix);
		OutputStream output = null;
		try {
			output = new FileOutputStream(temp);
			byte[] buf = new byte[1024];
			int bytesRead;
			while ((bytesRead = is.read(buf)) > 0) {
				output.write(buf, 0, bytesRead);
			}
		} finally {
			is.close();
			output.close();
		}

		return temp;
	}

	/**
	 * 复制文件到临时文件里 给定一个默认名称
	 * 
	 * @param is
	 *            文件输入流
	 * @return
	 * @throws Exception
	 */
	public static File copyResourceToTempFile(InputStream is) throws Exception {
		return copyResourceToTempFile("adcctemp" + System.currentTimeMillis(), ".tmp", is);
	}

	/**
	 * 获取文件后缀名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getSuffix(String filePath) {

		int len = filePath.length();
		int p = filePath.lastIndexOf(".");
		String suffix = (p >= 0 && p + 1 < len) ? filePath.substring(p + 1, len) : null;

		if (null != suffix && p > 0 && "gz".equals(suffix)) {
			int idx = filePath.lastIndexOf(".", p - 1);
			suffix = (idx >= 0 && idx + 1 < len) ? filePath.substring(idx + 1, len) : suffix;
		}

		return suffix;
	}
}
